import webview
import sys
from pathlib import Path
import db
import os
import subprocess
import upload
if getattr(sys, 'frozen', False):
    # 如果是打包后的程序
    base_path =  Path(sys._MEIPASS)
    html_url = f'file://{(base_path  / 'html' / 'index.html').as_posix()}'
    debugOpen = False
else:
    # 如果是开发环境
    html_url = 'http://localhost:5173/'
    debugOpen = True

# 拼接 assets 文件夹的路径

# !定义一个 Python 类，其中的方法将暴露给 JavaScript
class Api(db.Db):
    # 开始任务
    def startJob(self, jobIds):
        try:
            # jobIds 应该是个 jobId的数组
            # 先获取公共配置
            commService = self.getCommService()['data']
            # 获取任务列表
            jobList = self.getJobListByIds(jobIds)['data']
            self.updateJobStatusByIds(jobIds,'2')
            newList = []
            # 遍历字典 jobList
            for job in jobList:
                for key, value in commService.items():
                    if job[key] == '' or job[key] == None:
                        job[key] = value
                newList.append(job)
            
            # 先都改为执行中等待中  0 平常状态 1 待执行 2 执行中等待中 3 执行中 
            # 按顺序执行任务
            for job in newList:
                self.updateJobStatusByIds([job['id']],'3')
                buildInfo = {
                    'log': '',
                    'status': '1' # 1 成功 0 失败
                }
                if os.path.exists(job['dir']):
                    try:
                        os.chdir(job['dir'])
                        # 打包 命令
                        print(os.system(job['buildCommond']))
                        buildInfo['log'] = "打包完成;"
                        # 判断其他命令是否存在
                        otherCommond = job.get('otherCommond')
                        if otherCommond is not None and otherCommond != '':
                            try:
                                print(os.system(otherCommond))
                                buildInfo['log'] += "其他命令执行完成;"
                                buildInfo['status'] = '1'
                            except subprocess.CalledProcessError as e:
                                buildInfo['log'] += "其他命令执行失败: " + e.stderr
                                buildInfo['status'] = '0'
                        if buildInfo['status'] == '1':   
                            # 开始上传
                            try:
                                upload.upload_folder(job, buildInfo)
                                buildInfo['log'] += "上传完成;"
                                buildInfo['status'] = '1'
                            except subprocess.CalledProcessError as e:
                                buildInfo['log'] += "上传失败: " + e.stderr
                                buildInfo['status'] = '0' 
                    except subprocess.CalledProcessError as e:
                        buildInfo['log'] = "打包失败: " + e.stderr
                        buildInfo['status'] = '0'
                else:
                    buildInfo['log'] = f"指定的目录 {job['dir']} 不存在。"
                    buildInfo['status'] = '0'
                    print(f"指定的目录 {job['dir']} 不存在。")
                self.addJobLog({
                    'jobId': job['id'],
                    "status": buildInfo['status'],
                    'log': buildInfo['log']
                })
                self.updateJobStatusByIds([job['id']],'0')

            return "任务开始"
        except Exception as e:
            print(f"任务开始时出现错误: {e}")
            return None

def main():
    api = Api()
    # api.startJob([1])
    # # 创建一个 Web 视图窗口，并将 Api 类的实例暴露给 JavaScript
    window = webview.create_window('vane-v1.0.0', html_url, js_api=api,width=1500,height=900)
    webview.start(debug=debugOpen)


if __name__ == '__main__':
    main()
    #  pyinstaller --onefile --add-data "html/dist;html" --windowed .\index.py
    #  cd html ; npm run build ; cd .. ;pyinstaller --onefile --add-data "html/dist;html" .\index.py
